#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
真实数据获取测试脚本
测试各种真实数据源的可用性
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

import akshare as ak
import yfinance as yf
import pandas as pd
from datetime import datetime, timedelta

def test_akshare():
    """测试akshare数据源"""
    print("🧪 测试akshare数据源")
    print("-" * 40)
    
    test_stocks = ["000001", "000002", "600036"]
    
    for stock in test_stocks:
        print(f"\n📊 测试股票: {stock}")
        try:
            # 测试方法1: stock_zh_a_hist
            end_date = datetime.now()
            start_date = end_date - timedelta(days=30)
            
            print(f"   尝试方法1: stock_zh_a_hist")
            hist_data = ak.stock_zh_a_hist(
                symbol=stock,
                period="daily", 
                start_date=start_date.strftime('%Y%m%d'),
                end_date=end_date.strftime('%Y%m%d'),
                adjust="qfq"
            )
            
            if not hist_data.empty:
                print(f"   ✅ 成功获取数据: {len(hist_data)} 条")
                print(f"   📈 最新价格: {hist_data.iloc[-1]['收盘']:.2f}元")
                print(f"   📅 数据日期: {hist_data.iloc[-1]['日期']}")
            else:
                print(f"   ❌ 数据为空")
                
        except Exception as e:
            print(f"   ❌ 方法1失败: {e}")
            
            # 测试方法2: stock_individual_info_em
            try:
                print(f"   尝试方法2: stock_individual_info_em")
                info = ak.stock_individual_info_em(symbol=stock)
                if not info.empty:
                    current_price = info[info['item'] == '今开']['value'].iloc[0] if len(info[info['item'] == '今开']) > 0 else None
                    print(f"   ✅ 获取基本信息成功")
                    if current_price:
                        print(f"   📈 今开价格: {current_price}")
                else:
                    print(f"   ❌ 基本信息为空")
            except Exception as e2:
                print(f"   ❌ 方法2失败: {e2}")
                
                # 测试方法3: stock_zh_a_spot_em
                try:
                    print(f"   尝试方法3: stock_zh_a_spot_em")
                    spot_data = ak.stock_zh_a_spot_em()
                    if not spot_data.empty:
                        target_stock = spot_data[spot_data['代码'] == stock]
                        if not target_stock.empty:
                            current_price = target_stock.iloc[0]['最新价']
                            print(f"   ✅ 获取实时数据成功")
                            print(f"   📈 最新价格: {current_price:.2f}元")
                        else:
                            print(f"   ❌ 未找到股票 {stock}")
                    else:
                        print(f"   ❌ 实时数据为空")
                except Exception as e3:
                    print(f"   ❌ 方法3失败: {e3}")

def test_yfinance():
    """测试yfinance数据源"""
    print("\n🧪 测试yfinance数据源")
    print("-" * 40)
    
    # A股在yfinance中的格式
    test_stocks = {
        "000001": "000001.SZ",  # 平安银行
        "000002": "000002.SZ",  # 万科A  
        "600036": "600036.SS"   # 招商银行
    }
    
    for stock_code, yf_symbol in test_stocks.items():
        print(f"\n📊 测试股票: {stock_code} ({yf_symbol})")
        try:
            ticker = yf.Ticker(yf_symbol)
            hist = ticker.history(period="30d")
            
            if not hist.empty:
                print(f"   ✅ 成功获取数据: {len(hist)} 条")
                print(f"   📈 最新价格: {hist['Close'].iloc[-1]:.2f}元")
                print(f"   📅 最新日期: {hist.index[-1].strftime('%Y-%m-%d')}")
            else:
                print(f"   ❌ 数据为空")
                
        except Exception as e:
            print(f"   ❌ 失败: {e}")

def test_alternative_sources():
    """测试其他数据源"""
    print("\n🧪 测试其他数据源")
    print("-" * 40)
    
    # 测试akshare的其他接口
    try:
        print("📊 测试股票列表获取")
        stock_list = ak.stock_zh_a_spot_em()
        if not stock_list.empty:
            print(f"   ✅ 成功获取股票列表: {len(stock_list)} 只")
            # 显示前5只股票的信息
            for i in range(min(5, len(stock_list))):
                row = stock_list.iloc[i]
                print(f"   📈 {row['代码']} {row['名称']}: {row['最新价']:.2f}元")
        else:
            print(f"   ❌ 股票列表为空")
    except Exception as e:
        print(f"   ❌ 获取股票列表失败: {e}")

if __name__ == "__main__":
    print("🎯 开始真实数据源测试...")
    print("=" * 50)
    
    # 禁用代理
    import os
    proxy_vars = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']
    for var in proxy_vars:
        if var in os.environ:
            del os.environ[var]
    os.environ['NO_PROXY'] = '*'
    
    test_akshare()
    test_yfinance() 
    test_alternative_sources()
    
    print("\n" + "=" * 50)
    print("🎯 数据源测试完成！")
